package es.uc3m.setichat.android;

import java.util.ArrayList;
import java.util.List;

import es.uc3m.setichat.clases.SeTIChatContact;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.widget.ArrayAdapter;

public class SeTIChatContactsController {
	
	private ContentResolver contentResolver;
	private boolean DEBUG = false;
	private String[] contacts;
	private Context context;
	public  SeTIChatXMPPController xmppController;
	public static  ArrayList<SeTIChatContact> actual_contacts;
	private int layout;
	
	
	public SeTIChatContactsController(ContentResolver contentResolver,
			 Context context, SeTIChatXMPPController xmppController,boolean dEBUG) {
		super();
		this.contentResolver = contentResolver;
		DEBUG = dEBUG;
		this.context = context;
		this.xmppController = xmppController;
	}
	
	public SeTIChatContactsController(Context context,boolean dEBUG) {
		super();
		DEBUG = dEBUG;
		this.context = context;
	}
	


	public Void getContactsInitials(){
		Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
		contacts = new String[0];
		
    	AsyncTask<Uri,Void, Boolean> getContactAndroid = new AsyncTask<Uri,Void, Boolean>(){

    		@Override
    		protected Boolean doInBackground(Uri... contactUri) {
    			long contactId = -1;
    		
                Cursor cursor2,cursor = contentResolver.query(contactUri[0],
                        new String[]{Contacts._ID, Contacts.DISPLAY_NAME}, null, null, null);
                try {
                	while(cursor.moveToNext()){
                		contactId = cursor.getLong(0);
                        cursor2 = contentResolver.query(Phone.CONTENT_URI,
                                new String[]{Phone.NUMBER},
                                Phone.CONTACT_ID + "=" + contactId, null, Phone.IS_SUPER_PRIMARY + " DESC");
                        try {
                            if (cursor2.moveToFirst()) {
                            	String aux[] 				= new String[contacts.length+1];
                            	System.arraycopy(contacts,0,aux,0,contacts.length);
                            	contacts 						= aux;
                            	contacts[contacts.length-1] 	= cursor2.getString(0);
                            }
                        } finally {
                            cursor2.close();
                        }
                        
                	}
                } finally {
                    cursor.close();
                }
                
                return true;
            	
    		}
    		
    		@Override
    		protected void onPostExecute(Boolean kk) {
    			compareWithSQl();
    	    }
    		
    	};
    	    	
    	getContactAndroid.execute(intent.getData());
    	
    	return null;
	}
	
	private void compareWithSQl(){
		AsyncTask<Void,Void, Void> getContactSQL = new AsyncTask<Void,Void,Void>(){

    		@Override
    		protected Void doInBackground(Void... kk) {
    			SeTIChatSQLiteHelper setiDB = new SeTIChatSQLiteHelper(context, "BBDDSetichat", null, SeTIChatSQLiteHelper.SQL_VERSION); 
    			
    	        SQLiteDatabase db = setiDB.getReadableDatabase();
    	        Cursor c = db.query("contacts",new String[]{"telefono","nick"},null, null,null,null,"nick ASC");
    	        
    	        boolean exist = false;
    	        SeTIChatContact result[] = new SeTIChatContact[0];
    	        
    	        for(int i=0;i<contacts.length;i++){
    	        	exist = false;
    	        	c.moveToFirst();
    	        	while(!c.isAfterLast() && ! exist){
    	        		if(c.getString(0).equals(contacts[i])){
		        			exist = true;
		        		}
    	        		c.moveToNext();
    	        	}
    	        	if(!exist){
    	        		SeTIChatContact aux[] 		= new SeTIChatContact[result.length+1];
    	            	System.arraycopy(result,0,aux,0,result.length);
    	            	result 						= aux;
    	            	result[result.length-1] 	= new SeTIChatContact(contacts[i],"");
    	        	}
	        	}
    	        c.close();
    	        db.close();
    	        setiDB.close();
    	        sendContactRequest(result);
    	        
    	        return null;
    		}
    		
    		
    	};
		
    	getContactSQL.execute();
        
	}
	
	private void sendContactRequest(SeTIChatContact[] contactos){
		SeTIChatXMLController xml = new SeTIChatXMLController();
		String random_id = xml.generateRandomID();
		xmppController.sendMessage(xml.createContactRequest(contactos,random_id),random_id,"contact-request");
	}
	
	public void saveContacts(ArrayList<SeTIChatContact> contacts){
    			SeTIChatSQLiteHelper setiDB = new SeTIChatSQLiteHelper(context, "BBDDSetichat", null, SeTIChatSQLiteHelper.SQL_VERSION); 
    	        SQLiteDatabase db = setiDB.getWritableDatabase();
    	        if(db!=null){
    	        	for(int i=0;i<contacts.size();i++){
    	        		SQLiteStatement stmt = db.compileStatement("INSERT INTO contacts (telefono,nick) VALUES(?,?)");
    	        		stmt.bindString(1, contacts.get(i).getMobile());
    	        		stmt.bindString(2, contacts.get(i).getNick());
    	        		stmt.execute();
    	        	}
    	        }
    	        db.close();
    			setiDB.close();

	}
	
	public String[] printContacts(){
		SeTIChatSQLiteHelper setiDB = new SeTIChatSQLiteHelper(context, "BBDDSetichat", null, SeTIChatSQLiteHelper.SQL_VERSION); 
		
	    SQLiteDatabase db = setiDB.getReadableDatabase();
	    Cursor c = db.query("contacts",new String[]{"telefono","nick"},null, null,null,null,"nick ASC");
	
		String[] array_contacts = new String[0];
		c.moveToFirst();
		actual_contacts = new ArrayList<SeTIChatContact>();
		while(!c.isAfterLast()){
			SeTIChatContact contact = new SeTIChatContact(c.getString(0),c.getString(1));
			actual_contacts.add(contact);
			String[] aux = new String[array_contacts.length+1];
			System.arraycopy(array_contacts, 0, aux, 0, array_contacts.length);
			array_contacts  = aux;
			array_contacts[array_contacts.length-1] = c.getString(1);
			c.moveToNext();
		}
		
		c.close();
		db.close();
		setiDB.close();
		return array_contacts;
	}
	
	
	
}
